# -*- coding: utf-8 -*-
"""
@Time ： 2022/12/29 14:44
@Auth ： jiraWu
@File ：main..py
@IDE ：PyCharm
@Motto:人生苦短，我学Python

"""
"""
获取图片素材
1.请求对象封装
2.获取网页源码
3.下载 （前十页的数据）
https://sc.chinaz.com/tupian/fengjing.html
https://sc.chinaz.com/tupian/fengjing_{page}.html
https://scpic3.chinaz.net/Files/pic/pic9/202204/hpic5364_s.jpg
"""
from jira_wu_dev_utils._request import GetRequest
from lxml import etree
from urllib import request
from winsound import Beep


def create_req(page: int) -> str:
    """
    创建请求
    :param page: 页码
    :return: 响应内容
    """
    if page == 1:
        url = "https://sc.chinaz.com/tupian/taikongkexuetupian.html"
    else:
        url = f"https://sc.chinaz.com/tupian/taikongkexuetupian_{str(page)}.html"

    cont = GetRequest(url=url).send_req()
    return cont


def analysis_down_load(cont: str):
    """
    解析源码 并下载图片
    :param cont: 响应内容
    :return: None
    """
    tree = etree.HTML(cont)
    src_lis = tree.xpath(
        '//div[@class="tupian-list com-img-txt-list"]/div[@class="item"]/img[@class="lazy"]/@data-original')
    name_lis = tree.xpath(
        '//div[@class="tupian-list com-img-txt-list"]/div[@class="item"]/img[@class="lazy"]/@alt')
    src_lis_rep = []
    for src in src_lis:
        src_lis_rep.append(src.replace(r'//', 'https://'))
    for i in range(len(name_lis)):
        name = name_lis[i]
        src = src_lis_rep[i]
        print(name, src)
        # 下载
        GetRequest(src).down_load_file(filename=f'./素材/{name}.jpg')
        Beep(2000, 100)

if __name__ == '__main__':
    start_page = int(input("起始页码:"))
    end_page = int(input("结束页码:"))
    for page in range(start_page, end_page + 1):
        cont = create_req(page)
        analysis_down_load(cont)
